#!/usr/bin/python

"""evaluate.py

this script is
"""

__author__ = 'takahiro'
__version__ = '2014-02-10 1.00 (takahiro)'

import sys
import optparse

usage = "%prog [filename] <OPERATION BUY:1, SELL:0> <BEGIN_DATE_NUM> <END_DATE_NUM> <BEGIN_YORIHIKE HIKE:1, YORI:0> <END_YORIHIKE>"
parser = optparse.OptionParser( usage=usage )
parser.parse_args( )

BUY = 1
SELL = 0

HIKE = 1
YORI = 0

if len( sys.argv ) == 6:
  stream = sys.stdin
  OPERATION = int(sys.argv[1])
  BEGIN_NUM = int(sys.argv[2])
  END_NUM = int(sys.argv[3])
  BEGIN_YORIHIKE = int(sys.argv[4])
  END_YORIHIKE = int(sys.argv[5])
elif len( sys.argv ) == 7:
  stream = open( sys.argv[ 1 ], 'r' )
  OPERATION = int(sys.argv[2])
  BEGIN_NUM = int(sys.argv[3])
  END_NUM = int(sys.argv[4])
  BEGIN_YORIHIKE = int(sys.argv[5])
  END_YORIHIKE = int(sys.argv[6])
else:
  parser.print_help( )
  exit( )

def valid_param():
  if OPERATION != BUY and OPERATION != SELL:
    return False
  if BEGIN_NUM < 0:
    return False
  if END_NUM < 0:
    return False
  if BEGIN_YORIHIKE != YORI and BEGIN_YORIHIKE != HIKE:
    return False
  if END_YORIHIKE != YORI and END_YORIHIKE != HIKE:
    return False
  return True

if not valid_param():
  parser.print_help( )
  exit( )


keys = open('format.arg', 'r').readlines()[0].rstrip().split(' ')
keys.append('signal')

def get_yorihike_key(yorihike):
  if yorihike == YORI:
    return 'open'
  else:
    return 'close'
  

lines = []
signals = []

datas = []

for line in stream:
  array = line.rstrip().split('\t')
  datas.append(array)

begin_index = keys.index(get_yorihike_key(BEGIN_YORIHIKE))
end_index = keys.index(get_yorihike_key(END_YORIHIKE))

for i, v in enumerate(datas):
  signal = int(v[keys.index('signal')])
  if signal != 1:
    continue
  begin_op_index = i + BEGIN_NUM
  end_op_index = i + END_NUM
  if begin_op_index >= len(datas) or end_op_index >= len(datas):
    continue

  date = datas[i][keys.index('date')]
  begin_value = int(datas[begin_op_index][begin_index])
  end_value = int(datas[end_op_index][end_index])

  if OPERATION == BUY:
    result = end_value - begin_value
  else:
    result = begin_value - end_value
  print '%s\t%d' % (date, result)

